/*
 * Copyright 2009 Paul Loy
 * 
 * This file is part of java-mod-auth-token-urigen, a library to allow users to
 * create mod_auth_token compatible uris in Java.
 * 
 * java-mod-auth-token-urigen is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * java-mod-auth-token-urigen is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with java-mod-auth-token-urigen.  If not, see <http://www.gnu.org/licenses/>.
 */
 
package com.keteracel.auth;

import com.keteracel.util.MD5Digester;

/**
 * @author Paul_Loy (keteracel)
 */
public class ApacheAuthToken {
	
	private final String token;
	private final String timestamp;
	private final String authpath;
	private final String filepath;

	/**
	 * Creates an ApacheAuthToken object, from which you can get a valid mod_auth_token uri
	 * using {@link #toUriString()}.
	 * 
	 * @param secret The secret key shared by your apache httpd.conf and this application.
	 * @param authpath The path used in your httpd.conf Location directive.
	 * @param filepath The path to the file you wish to request through the auth.
	 */
	public ApacheAuthToken(String secret, String authpath, String filepath) {
		this(secret, authpath, filepath, System.currentTimeMillis());
	}

	/**
	 * Do not use. For testing only.
	 */
	protected ApacheAuthToken(String secret, String authpath, String filepath, long time) {
		this.timestamp = Long.toHexString(time/1000L);
		this.authpath = authpath;
		this.filepath = sanitizeFilePath(filepath);
		this.token = generateToken(secret);
	}

	/**
	 * Make sure filepaths begin with a slash
	 * @param fpath
	 * @return
	 */
	private String sanitizeFilePath(String fpath) {
		if (fpath.charAt(0) != '/') {
			fpath = '/' + fpath;
		}
		return fpath;
	}

	private String generateToken(String secret) {
		return MD5Digester.toMD5(secret+filepath+timestamp);
	}

	public String getToken() {
		return token;
	}

	public String getTimestamp() {
		return timestamp;
	}

	public String toString() {
		return toUriString();
	}

	public String toUriString() {
		return authpath + "/" + token + "/" + timestamp + filepath;
	}
}
